package com.erp.erp_project.core.aop;

import com.erp.erp_project.core.annotation.Permission;
import com.erp.erp_project.core.exception.CheckException;
import com.erp.erp_project.core.exception.CustomException;
import com.erp.erp_project.model.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author yh
 */
@Component
@Aspect
public class PowerInterceptor {

    @Pointcut("execution(public * com.erp.erp_project.controller..*.*(..))")
    public void powerMethod() {

    }

    @Before("powerMethod()")
    public void check(JoinPoint joinPoint) throws CheckException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session=attr.getRequest().getSession(true);
        User user = (User)session.getAttribute("user");
        if(targetMethod!=null){
            Permission permission=targetMethod.getAnnotation(Permission.class);
            if(permission!=null){

                if(!user.getRole().getRoleName().equals("超级管理员")){
                    if(user.getRole().getRoleLockout()==0){
                        throw new CheckException("<p style=\"color: #2D93CA; font-size: 20px;\">用户的角色权限被锁定不能操作，请联系超级管理员解除锁定再操作</p>");
                    }else{
                        if(user.getUserLockout()==0){
                            throw new CheckException("<p style=\"color: #2D93CA; font-size: 20px;\">用户被锁定不能操作，请联系超级管理员解除锁定再操作</p>");
                        }else {
                            String name=permission.value();
                            List<String> checkpowers = (List<String>)session.getAttribute("checkpowers");
                            if(!checkpowers.contains(name)){
                                throw new CheckException("<p style=\"color: #2D93CA; font-size: 20px;\">对不起您没有"+name+"的权限，请联系超级管理员提升权限再操作</p>");
                            }
                        }
                    }
                }

            }
        }


    }

}
